package com.dbgs.insurance.insuredperson.http;

import android.content.Intent;

import com.dbgs.insurance.insuredperson.MyApplication;
import com.dbgs.insurance.insuredperson.activity.LoginActivity;
import com.hss.base.events.EventFinshActivity;
import com.hss.base.interfaces.IHttpCallBack;
import com.wondersgroup.insurance.datalibrary.result.ResultBaseBean;

import org.greenrobot.eventbus.EventBus;

import rx.Subscriber;


/**
 * Created by WuXiaolong
 * on 2016/9/22.
 * github:https://github.com/WuXiaolong/
 * weibo:http://weibo.com/u/2175011601
 * 微信公众号：吴小龙同学
 * 个人博客：http://wuxiaolong.me/
 */
public abstract class ApiCallback<M extends ResultBaseBean> extends Subscriber<M> implements IHttpCallBack<M> {
    public final static short RELOGIN_CODE = 1003;



    @Override
    public void onError(Throwable e) {
        onFailure("网络异常");
//        e.printStackTrace();
//        if (e instanceof HttpException) {
//            HttpException httpException = (HttpException) e;
//            //httpException.response().errorBody().string()
//            int code = httpException.code();
//            String msg = httpException.getMessage();
////            LogUtil.d("code=" + code);
//            if (code == 504) {
//                msg = "网络不给力";
//            }
//            if (code == 502 || code == 404) {
//                msg = "服务器异常，请稍后再试";
//            }
//            onFailure(msg);
//        } else {
//            onFailure(e.getMessage());
//        }
        onFinish();
    }

    @Override
    public void onNext(M result) {
        if (result !=null ){
            if ( result.success == true){

                onSuccess(result);
            }
            else if (result.code == RELOGIN_CODE){
                onExitLogin();

                Intent loginIntnet = new Intent();
                loginIntnet.setClass(MyApplication.getInstance(), LoginActivity.class);
                MyApplication.getInstance().startActivity(loginIntnet);
                EventFinshActivity eventFinshActivity = new EventFinshActivity();
                eventFinshActivity.aliveActivityName = LoginActivity.class.getSimpleName();
                EventBus.getDefault().post(eventFinshActivity);
            }
            else {
                onDataErr(result.message == null ? "数据异常":result.message);
            }
        }else {
            onDataErr("数据异常");
        }
        onFinish();
    }

    @Override
    public void onCompleted() {
        onFinish();
    }
}
